package top.milkbox.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.milkbox.info.R;
import top.milkbox.utils.GuoUtilsIp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Component
public class IpBlacklistInterceptor extends BaseInterceptor implements HandlerInterceptor {

    @Value("#{'${info.ip-blacklist}'.split('|')}")
    private List<String> blacklist;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = GuoUtilsIp.getRealIp(request);
        for (String blackIp : blacklist) {
            if (ip.equals(blackIp)) {
                log.warn("ip地址（" + ip + "）被加入黑名单，拒绝访问");
                response.setContentType("application/json;charset=utf-8");
                objectMapper.writeValue(response.getWriter(), new R(false, null,
                        "抱歉，您已被加入黑名单。Sorry, you have been to join blacklist."));
                return false;
            }
        }
        log.debug("ip：" + ip + "，" +
                "地址：" + request.getRequestURL() + "，" +
                "方式：" + request.getMethod() + "，" +
                "来源：" + request.getHeader("Referer")); // TODO 这里可能会打印很多
        return true;
    }
}
